﻿using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using NP.BPMReportPlatform.BPMPlatform;
using NP.BPMReportPlatform.DBHelper;
using NP.BPMReportPlatform.Entities.BPM_Business;
using NP.BPMReportPlatform.Entities.BPM_Business.AccountOpenChange;
using NP.BPMReportPlatform.Entities.BPM_Platform;
using NP.BPMReportPlatform.PR.Dto;
using NP.BPMReportPlatform.Utils;
using SqlSugar;
using Volo.Abp.Application.Dtos;

namespace NP.BPMReportPlatform.PR
{
    public class PRService : BPMReportPlatformAppService, IPRService
    {
        private readonly SqlSugarClient _db;
        private readonly SqlSugarClient _dbPlatform;
        private readonly IBPMUtilsAppService _bPMUtilsApp;
        private readonly IBPMPlatformAppService _iBPMPlatformApp;

        public PRService(ISqlSugarAppService sqlSugarAppService, IBPMUtilsAppService bPMUtilsApp
            , IBPMPlatformAppService iBPMPlatformApp)
        {
            _db = sqlSugarAppService.GetBusinessInstance();
            _dbPlatform = sqlSugarAppService.GetPlatformInstance();
            _bPMUtilsApp = bPMUtilsApp;
            _iBPMPlatformApp = iBPMPlatformApp;
        }

        public async Task<PagedResultDto<GetAccountOpenChangeOutput>> GetAllAsync(GetAccountOpenChangeInput input)
        {
            RefAsync<int> totalCount = 0;

            var listQueryable = GetQueryable(input);
            var listViewDto = await listQueryable.ToPageListAsync(input.PageIndex, input.PageSize, totalCount);

            var userId = await _iBPMPlatformApp.GetUserAsync(CurrentUser.UserName);

            listViewDto.ForEach(x => x.Url = _bPMUtilsApp.GetProcessUrl(x.InstanceNumber, userId));

            //返回结果
            return new PagedResultDto<GetAccountOpenChangeOutput>()
            {
                TotalCount = totalCount,
                Items = listViewDto
            };
        }

        public async Task<List<GetAccountOpenChangeOutput>> ExportAsync(GetAccountOpenChangeInput input)
        {
            var listQueryable = GetQueryable(input);
            var listViewDto = await listQueryable.ToListAsync();
            return listViewDto;
        }


        private ISugarQueryable<GetAccountOpenChangeOutput> GetQueryable(GetAccountOpenChangeInput input)
        {
            var currentUserId = Guid.Empty;
            if (!input.IsQueryAll)
            {
                var currentUserDto = _dbPlatform.Queryable<Users>().Where(x => x.WorkNumber.Equals(CurrentUser.UserName)).First();
                if (currentUserDto != null)
                {
                    currentUserId = currentUserDto.UserId;
                }
            }
            var listQueryable = _db.Queryable<AccountOpenChangeHeader, BusinessProcessesNew>(
                     (x, b) => new JoinQueryInfos(JoinType.Left, x.InstanceNumber == b.InstanceId))
                .WhereIF(!input.IsQueryAll, x => x.AddUserId.Equals(currentUserId))
                .WhereIF(!string.IsNullOrWhiteSpace(input.InstanceNumber),x => x.InstanceNumber == input.InstanceNumber)
                .WhereIF(!input.OrderStatus.IsNullOrEmpty(), (x, b) => SqlFunc.ContainsArray(input.OrderStatus.ToArray(), b.ProcessStatusCode))
                .WhereIF(!string.IsNullOrWhiteSpace(input.AddUserName), x => x.AddUserName.Contains(input.AddUserName))
                .WhereIF(input.StartCreationTime != null && input.EndCreationTime != null,
                    x => x.AddTime >= input.StartCreationTime && x.AddTime.AddDays(-1) <= input.EndCreationTime)
                 .WhereIF(!string.IsNullOrWhiteSpace(input.OperationType), x => x.OperationType == input.OperationType)
                 .WhereIF(!string.IsNullOrWhiteSpace(input.PrincipalName), x => x.PrincipalName == input.PrincipalName)
                 .WhereIF(!string.IsNullOrWhiteSpace(input.PlatformName), x => x.PlatformName == input.PlatformName)
                 .WhereIF(!string.IsNullOrWhiteSpace(input.PlatformName), x => x.PlatformName == input.PlatformName)
                 .WhereIF(input.ExpiryDateStart != null && input.ExpiryDateEnd != null,
                    x => Convert.ToDateTime(x.ExpiryDateStart) >= input.StartCreationTime && Convert.ToDateTime(x.ExpiryDateEnd) <= input.EndCreationTime)
                 .WhereIF(!string.IsNullOrWhiteSpace(input.AdminName), x => x.AdminName == input.AdminName)
                 .WhereIF(!string.IsNullOrWhiteSpace(input.Sn), x => x.Sn.Contains(input.Sn))
                .Select((x, b) => new GetAccountOpenChangeOutput()
                {
                    InstanceNumber = x.InstanceNumber,
                    CreateTime = x.AddTime,
                    AddUserName = x.AddUserName,
                    OrderStatus = b.ProcessStatusName,
                    UserOrganization =x.UserOrganization,
                    OperationType = x.OperationType,
                    IsAuthen = x.IsAuthen,
                    ApplyAccount = x.ApplyAccount,
                    PrincipalName = x.PrincipalName,
                    UseReason = x.UseReason,
                    PlatformName = x.PlatformName,
                    ExpiryDateStart1 = x.ExpiryDateStart1,
                    ExpiryDateEnd1 = x.ExpiryDateEnd1,
                    ExpiryDateStart = x.ExpiryDateStart,
                    ExpiryDateEnd = x.ExpiryDateEnd,
                    IsAgent = x.IsAgent,
                    AgentName = x.AgentName,
                    Purpose = x.Purpose,
                    Cost = x.Cost,
                    AdminAccount = x.AdminAccount,
                    AdminName = x.AdminName,
                    AdminTelephone = x.AdminTelephone,
                    Remark = x.Remark,
                    Sn = x.Sn,
                }).MergeTable().Distinct().OrderBy(ins => ins.CreateTime, OrderByType.Desc);
            return listQueryable;
        }

        public async Task<List<AccountOpenChangeResult>> GetAccounts()
        {
            return await _db.Queryable<AccountOpenChangeResult>().Where(x => !x.InstanceNumber.StartsWith("P"))
                .Select(x => new AccountOpenChangeResult
                {
                    Sn = x.Sn,//账号编号
                    ApplyAccount = x.ApplyAccount,//账号名称
                    PlatformName = x.PlatformName,//平台名称 抖音/微博 等等
                    SubPlatformName = x.SubPlatformName,//平台子名称 公众号/视频号/小程序/店铺 等等
                    UserOrganization = x.UserOrganization,//组织架构（立邦中国_TUC事业群_新零售事业部_抖快运营部_达人推广组），没有存单独的部门
                    AdminUserId = x.AdminUserId,//管理员用户Id
                    AdminWorkNumber = x.AdminWorkNumber,//管理员工号
                    AdminName = x.AdminName,//管理员姓名
                    AdminTelephone = x.AdminTelephone,//管理员手机号码
                }).ToListAsync();
        }
    }
}